import { useEffect, useRef, useState } from 'react';
import clsx from 'clsx';
import { AiIcon, DigestIcon, EnterIcon, ExplainIcon, SummarizeIcon, TranslateIcon, PencilIcon } from '@/compnents/icons';
import { ContentAIPlugin, ContentAIView } from './content-ai-plugin';
import type { ContentAIPluginProps } from './content-ai-plugin';
import './content-ai.less';

// 指定某个属性变为可选而其它属性不变
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;

export type ContentAIProps = Omit<Optional<ContentAIPluginProps, 'pluginKey'>, 'element' | 'editor'> & {
  editor: ContentAIPluginProps['editor'] | null;
  className?: string;
};

export const ContentAI = (props: ContentAIProps) => {
  const [value, setValue] = useState('');
  const elementRef = useRef<HTMLDivElement | null>(null);
  const viewRef = useRef<ContentAIView | null>(null);

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };

  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    viewRef.current?.onKeyDown?.(e as any);
  };

  useEffect(() => {
    if (!elementRef.current) return;

    if (props.editor?.isDestroyed) return;

    const { pluginKey = 'contentAI', editor, tippyOptions = {}, shouldShow = null } = props;

    if (!editor) return console.warn('ContentAI 组件需要编辑器实例');

    const plugin = ContentAIPlugin({
      editor: editor,
      element: elementRef.current,
      pluginKey,
      shouldShow,
      autoFocusSelector: '.smap-ai-input input',
      tippyOptions: { maxWidth: 'max-content', ...tippyOptions },
      getView: (view) => (viewRef.current = view),
    });
    editor.registerPlugin(plugin);
    return () => editor.unregisterPlugin(pluginKey);
  }, [props.editor]);

  return (
    <div ref={elementRef} className={clsx(props.className, 'smap-editor-content-ai')} style={{ visibility: 'hidden' }}>
      <div className="smap-alternate-ai-ui smap-dropdown search">
        <div className="smap-search-wrap">
          <AiIcon />
          <div className="smap-ai-input">
            <input onKeyDown={onKeyDown} value={value} onChange={onChange} placeholder="问AI任何事情..." />
          </div>
          <EnterIcon />
        </div>
      </div>
      <div className="smap-alternate-ai-ui smap-dropdown popover">
        <div>
          <PencilIcon />
          <div className="smap-ellipsis title">继续写作</div>
        </div>
        <div>
          <SummarizeIcon />
          <div className="smap-ellipsis title">总结</div>
        </div>
        <div>
          <DigestIcon />
          <div className="smap-ellipsis title">摘要</div>
        </div>
        <div>
          <ExplainIcon />
          <div className="smap-ellipsis title">解释</div>
        </div>
        <div>
          <TranslateIcon />
          <div className="smap-ellipsis title">翻译</div>
        </div>
      </div>
    </div>
  );
};
